package com.jamie.jvm.thread;

import java.util.concurrent.CountDownLatch;

/**
 * 多线程计数器
 * @author jamie
 * @date 2021/3/9 22:18
 */
public class CountDownLatchDemo {

    public static void main(String[] args) throws InterruptedException {
        countDownLatchDemo1();
    }

    /**
     * 多线程计数器CountDownLatchDemo
     */
    private static void countDownLatchDemo1() throws InterruptedException {
        // 生成总数为6的计数器
        CountDownLatch countDownLatch = new CountDownLatch(6);
        for(int i = 1; i <= 6; i++){
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "\t 上完自学，离开教室");
                // 每执行一个线程减1
                countDownLatch.countDown();
            }, "Thread-" + i).start();
        }
        // 阻塞着，只有计数器为0时，才会继续执行
        countDownLatch.await();
        System.out.println(Thread.currentThread().getName() + "\t 班长最后关灯走人");
    }

    private static void countDownLatchDemo2() throws InterruptedException {
        // 生成总数为6的计数器
        CountDownLatch countDownLatch = new CountDownLatch(6);
        for(int i = 1; i <= 6; i++){
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "\t 国被灭");
                // 每执行一个线程减1
                countDownLatch.countDown();

            }, CountryEnum.forEachCountryEnum(i).getResMessage()).start();
        }
        // 阻塞着，只有计数器为0时，才会继续执行
        countDownLatch.await();
        System.out.println(Thread.currentThread().getName() + "\t 秦国，一统华夏");
    }

}
